<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="../js/ajax.js"></script>
    <style>
        div {
            user-select: none;
        }

        .right {
            font-size: 12px;
            color: green;
        }

        .err {
            font-size: 12px;
            color: red;
        }
    </style>
</head>

<body>
    <form onsubmit="return false">
        <p>
            <label for="user">用户名:</label>
            <input type="text" id="user" placeholder="用户名">
            <span id="user_span"></span>
        </p>

        <p>
            <input type="submit" id="btn" value="注册">
        </p>
    </form>
</body>

<script>

    // 1. 获取元素 
    var userInp = document.getElementById("user");
    var userSpan = document.getElementById("user_span");



    // 用户名:   由数字,字母 下划线组成,6-12位,且不能以数字开头
    // 一步到位
    userInp.onblur = function () {
        var user = userInp.value.trim();
        userInp.value = user;
        isUserOk = false; // 每次验证 默认还原为false

        var reg = /^[a-zA-Z_]\w{5,11}$/;

        if (reg.test(user)) {

            debugger;
            var p = isExistUser({ user });  // 发送请求 => 得到Promise实例(进行中)
            console.log(p);
            p.then(function (msg) {  // 请求成功时执行的内容
                userSpan.textContent = "√";
                userSpan.className = "right";
                isUserOk = true;
            }, function (msg) { // 请求失败时执行的内容
                userSpan.textContent = msg;
                userSpan.className = "err";
            })


        } else {
            userSpan.textContent = "用户名由数字、字母、下划线组成,6-12位,且不能以数字开头";
            userSpan.className = "err";
        }
    }

    // 调用此方法 => 进行中状态的Promise实例  => 异步操作有结果之后 才会改变当前Promise实例的状态
    function isExistUser(params) {  //{user}
        var p = new Promise(function (resolve, reject) {
            $.ajax({
                type: "get",
                url: "../php/isExistUser.php",
                data: {
                    ...params
                },
                dataType: "json",
                success: function (result) {
                    var { status, msg } = result;
                    if (status) {
                        resolve(msg);
                    } else {
                        reject(msg);
                    }
                    console.log(p);
                }
            })
        })
        return p;  //{pending}
    }

</script>

</html>